package servlet;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Collections;
import java.util.HashMap;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import objects.cluster.ClusterInfo;
import objects.user.UserInfo;
import ssh.SSHUtils;
import utils.Utils;
import database.ConnectionManager;
import database.Database;
import filesystem.FileSystem;


/**
 * Servlet implementation class InitServlet
 */
public class InitServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
	public void init(ServletConfig config) throws ServletException {
		doInit();
		super.init(config);
    }
	
	public static void doInit() {
		System.out.println("Initializing web application");
		try {
			
			new ConnectionManager();
			new Thread(Utils.sched).start();
			
			Connection conn = ConnectionManager.ds.getConnection();
			String query = "SELECT * FROM users";
			PreparedStatement stmt = conn.prepareStatement(query);
			ResultSet rs = stmt.executeQuery();
			while (rs.next()) {
				String username = rs.getString("name");
				String passwd = rs.getString("password");
				String email = rs.getString("email");
				int id = rs.getInt("id");
				UserInfo ui = new UserInfo(username, passwd, email, id);
				Database.users.put(username, ui);
				Database.getUserClusters(ui);
				Database.getFilesystem(ui);
				//SSHUtils.buildFileSystem(username,  passwd, "~/", ui, 0);
				Utils.out("+ ADDED " + username + " " + email + " to users table");
			}
		} catch (Exception e) {
			e.printStackTrace();
			//System.exit(0);
		}

	}

}
